<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;
use think\Loader;

class Phone extends Model
{
    /**
     * 获取客户资料列表
     * @param str $where <查询条件>
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
     * @return array <日报列表信息>
     */
    public function phonePoolData($where,$page,$limit,$tables)
    {
        $menuname = "Phone Pool";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $count = Db::name($tables)->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $customerList = Db::name($tables)->where($where)->limit(($page-1)*$limit,$limit)->order('createtime DESC')->select();
        // print_r($customerList);exit;
        foreach ($customerList as &$val) {
            // print_r($_SESSION);exit;
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
                    $val["telephone"] = substr($val["telephone"],0,3)."*****".substr($val["telephone"],-2);
                }
            }
        }
        $rowsList = count($customerList) ? $customerList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        return $arrData;
    }



    /**
     * 删除客户资料
     * @param  str $customer_code [客户资料id]
     * @return json    [删除状态]
     */
    public function delPhonePool($customer_code,$tables)
    {

        // print_r($tables)
        $result = Db::name($tables)->where('customer_code',$customer_code)->delete();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 导入客户资料
     * @return json 导入状态
     */
    public function importExcel()
    {
        set_time_limit(0);
        Loader::import('PHPExcel.Classes.PHPExcel');
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
        //获取表单上传文件
        $file = request()->file('excel');
        $info = $file->validate(['ext' => 'xls'])->move(ROOT_PATH . 'public' . DS . 'uploads');//上传验证后缀名,以及上传之后移动的地址
        // print_r($info);exit;
        if ($info) {
            // echo $info->getFilename();
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath;   //上传文件的地址
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            // echo "<pre>";
            //var_dump($excel_array);exit;
            // excel去重
            $data = [];
            foreach($excel_array as $v) {
                $data[$v[1]] = $v;
            }
            // $result = Db::name('vip_customer_basic')->insertAll($data); //批量插入数据
            $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
            $orderSn = $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
            $i = 10000;
            // 清空表
            $sql = "TRUNCATE table xy_vip_phone_pool";
            Db::execute($sql); // 清空表
            // 拼接SQL 
            $sql = "INSERT INTO xy_vip_phone_pool(name, phone, import_address, import_mark, createtime, customer_code) VALUES ";
            foreach ($data as $val) {
                $sql .= '("'.$val[0].'","'.$val[1].'", "'.$val[2].'","'.$_REQUEST['import_mark'].'","'.date('Y-m-d H:i:s').'", "'.($orderSn.$i).'"),';
                $i++;
            }
            $sql = rtrim($sql, ',');
            // echo $sql;exit;
            $result = Db::execute($sql);
            if ($result){
                echo json_encode(array('success'=>true,'msg'=>'导入成功！'));
                $this->mergePhonePool();
            } else {
                echo json_encode(array('msg'=>'导入失败！'));
            }
        } else {
            echo json_encode(array('msg'=>'导入失败！'));
        }
    }


    /**
     * 从导入的表中提取出来, 放入号码池a 去重
     */
    public function mergePhonePool ()
    {
        $phone = Db::name('vip_phone_pool')->select();
        foreach ($phone as $val) {
            $merge = Db::name('vip_phone')->where('phone="'.$val['phone'].'"')->find();
            // 空的插入 有值去重
            if (empty($merge)) {
                Db::name('vip_phone')->insert(array('phone'=>$val['phone']));
                Db::name('vip_phone_pool_a')->insert($val);
            } else {
                continue;
            }
        }
    }


    /**
     * 获取当前所有任务
     * @return array 任务数据
     */
    public function outBoundTask()
    {
        $taskList = Db::table('bgcrm.sales_task')->field('id,name')->order('createtime DESC')->select();
        return $taskList;
    }


    public function phoneCount ($tables) 
    {
        $count = Db::name("vip_phone_pool_$tables")->count();
        return $count;
    }


    public function transferCustomer ($tables)
    {
        $id = $_REQUEST['id'];
        $customerList = Db::name($tables)->field('customer_code, name, phone, import_mark, import_address')->limit($_REQUEST['limit'])->select();
        
        foreach ($customerList as $key => $val) {
            $data = array(
                'customer_code' => $val['customer_code'],
                'name' => $val['name'],
                'import_mark' => $_REQUEST['import_mark'],
                'phone1' => $val['phone'],
                'address' => $val['import_address'],
                'createtime' =>date('Y-m-d H:i:s'),
            );
            $result[] = Db::table("bgcrm.sales_source_$id")->insert($data);
            Db::name($tables)->where('customer_code="'.$val['customer_code'].'"')->delete();
        }

        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'操作成功！'));
        } else {
            echo json_encode(array('msg'=>'操作失败！'));
        }


    }


}